import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/sess")
public class SessionServlet extends HttpServlet {
    private  static final String SESSION_USER_KEY="SESSION_USER_KEY";
   //读session
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //1.得到session对象[false:有回话返回session对象，没有回话返回null]
        //true: 有回话返回session对象，没有回话创建一个回话）回话=登录
        HttpSession session=req.getSession(false);
        if(null==session){
            //没有登录
            resp.getWriter().println("抱歉，尚未登录呀!");
        }else{
            //已登录，打印用户的信息
            //2.从session中得到关联的对象
            User user=(User) session.getAttribute(SESSION_USER_KEY);
            resp.getWriter().println("登录成功|"+user);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String result="操作失败";
        //1.得到session
        HttpSession session=req.getSession(true);
        if(null!=session){//得到（或）创建了回话
            //2.将用户对象存储在session中
            User user=new User();
            user.setName("admin");
            user.setPassword("admin");
            session.setAttribute(SESSION_USER_KEY,user);
            result="Session写入成功！";
        }
        resp.getWriter().println(result);
    }
}
